//
//  GCD_Vc.m
//  Project_Demo
//
//  Created by Leon on 2018/7/1.
//  Copyright © 2018年 caoxiaozhu. All rights reserved.
//

#import "GCD_Vc.h"

@interface GCD_Vc ()
@property(nonatomic,strong)UIButton *btn;

@end

@implementation GCD_Vc

- (void)viewDidLoad {
    [super viewDidLoad];

//    [self test1];
    [self test2];
    
}

/*
 需求:下载3张图片, 等三张图片都下载完成再请求其他接口
 分析:使用Dispatch Group追加block到Global Group Queue,这些block如果全部执行完毕，就会执行Main Dispatch Queue中的结束处理的block
 */
-(void)test1{
    dispatch_queue_t queue = dispatch_queue_create("my.concurrent.queue", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        [NSThread sleepForTimeInterval:0.5];
        NSLog(@"下载1------%@",[NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        [NSThread sleepForTimeInterval:0.5];
        NSLog(@"下载2------%@",[NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        [NSThread sleepForTimeInterval:0.5];
        NSLog(@"下载3------%@",[NSThread currentThread]);
    });
    
    dispatch_barrier_async(queue, ^{
        NSLog(@"下载4------%@",[NSThread currentThread]);
    });
    
    dispatch_async(queue, ^{
        NSLog(@"下载5------%@",[NSThread currentThread]);
    });
}


//模拟下载完所有的值再显示在view上
-(void)test2{
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_group_t group = dispatch_group_create();
    
    static NSString *str1 = @"";
    static NSString *str2 = @"";
    static NSString *str3 = @"";
    
    dispatch_group_async(group,queue, ^{
        [NSThread sleepForTimeInterval:2];
        NSLog(@"下载1------%@",[NSThread currentThread]);
        str1 = @"123";
    });
    
    dispatch_group_async(group,queue, ^{
        [NSThread sleepForTimeInterval:2];
        NSLog(@"下载2------%@",[NSThread currentThread]);
        str2=@"223";
    });
    
    dispatch_group_async(group,queue, ^{
        [NSThread sleepForTimeInterval:2];
        NSLog(@"下载3------%@",[NSThread currentThread]);
        str3 = @"323";
    });
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        NSLog(@"下一步操作");
    });
    
    dispatch_group_async(group,queue, ^{
        [NSThread sleepForTimeInterval:2];
        
        dispatch_sync(dispatch_get_main_queue(), ^{
            UILabel *label = [UILabel new];
            label.backgroundColor = Color_Red;
            label.frame = CGRectMake(100, 100, 200, 30);
            label.text = [NSString stringWithFormat:@"%@,%@,%@",str1,str2,str3];
            [self.view addSubview:label];
        });
    });
}


@end
